# -*- coding: utf-8 -*-

import json

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.decorators.http import require_POST
from django.views.generic import TemplateView

from common.console import db as user_db
from common.mch import admin_db as mch_db
from common.mch.model import MCH_NOT_DELETED
from common.utils import track_logging
from common.utils.api import check_params
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.tz import utc_to_local_str

_LOGGER = track_logging.getLogger(__name__)


class MchView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        query_dct['deleted'] = str(MCH_NOT_DELETED)
        cond = user_db.get_mchids_filter_by_user(req.user_id)
        if cond and not query_dct.get('id'):
            query_dct['id'] = cond
        _LOGGER.info('MchView get query_dct : %s', query_dct)
        items, total_count = mch_db.list_mch(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            data.pop('password', None)
            data.pop('api_key', None)
            resp_items.append(data)
        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        param_dct = json.loads(req.body)
        mch = mch_db.create_mch(param_dct)
        return {}

    def delete(self, req, mch_id):
        mch_db.delete_mch(int(mch_id))
        _LOGGER.info('delete mch: %s, user: %s', mch_id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(MchView, self).dispatch(*args, **kwargs)


class SingleMchView(TemplateView):
    def get(self, req, mch_id):
        mch = mch_db.get_mch(id=int(mch_id))

        data = mch.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    def post(self, req, mch_id):
        return self.put(req, mch_id)

    def put(self, req, mch_id):
        query_dct = json.loads(smart_unicode(req.body))
        mch_db.upsert_mch(query_dct, int(mch_id))
        return {}

    def delete(self, req, mch_id):
        mch_db.delete_mch(int(mch_id))
        _LOGGER.info('delete mch: %s, user: %s', mch_id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleMchView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
def update_status(req, mch_id):
    ''' 调整商户状态 '''
    param_dct = json.loads(req.body)
    check_params(param_dct, ['enabled'])
    status = param_dct['enabled']
    mch_db.update_status(int(mch_id), status)
    _LOGGER.info('update mch: %s, by %s', mch_id, req.user.id)
    return {}
